package com.heima.search.service.impl;

import com.heima.common.constants.es.EsConstants;
import com.heima.common.exception.CustException;
import com.heima.es.service.EsService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDTO;
import com.heima.model.search.vos.SearchArticleVO;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.service.ApUserSearchService;
import com.heima.search.service.ArticleSearchService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ArticleSearchServiceImpl implements ArticleSearchService {

    @Value("${file.oss.web-site}")
    String website;

    @Value("${file.minio.readPath}")
    String readPath;

    @Autowired
    EsService esService;

    @Autowired
    ApUserSearchService apUserSearchService;

    /**
     ES文章分页搜索
     @return
     */
    @Override
    public ResponseResult search(UserSearchDTO userSearchDto) {
        //1 参数检查
        String searchWords = userSearchDto.getSearchWords();
        if (userSearchDto == null || StringUtils.isBlank(searchWords)) {
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //===================  记录搜索历史记录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user != null) {
            userSearchDto.setUserId(user.getId());
        }
        // 异步调用保存用户输入关键词记录
        apUserSearchService.insert(userSearchDto);

        if (userSearchDto.getPageSize() <= 0) {
            userSearchDto.setPageSize(10);
        }

        if (userSearchDto.getMinBehotTime() == null) {
            userSearchDto.setMinBehotTime(new Date());
        }
        //2 构建查询条件执行查询
        SearchSourceBuilder builder = new SearchSourceBuilder();
        // 构建查询条件和过滤等
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        // 关键词查询
        boolQueryBuilder.must(QueryBuilders.matchQuery("title", searchWords));
        // 查询小于mindate的数据
        boolQueryBuilder.filter(QueryBuilders.rangeQuery("publishTime").lt(userSearchDto.getMinBehotTime().getTime()));
        builder.query(boolQueryBuilder);
        // 按照发布时间倒序
        builder.sort("publishTime", SortOrder.DESC);
        // 分页
        builder.from(0);
        builder.size(userSearchDto.getPageSize());
        // 高亮 三要素
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title")
                .preTags("<font style='color: red; font-size: inherit;'>")
                .postTags("</font>");
        builder.highlighter(highlightBuilder);

        PageResponseResult searchResult = esService.search(builder, SearchArticleVO.class, EsConstants.ARTICLE_INDEX_NAME);
        //4 返回结果 staticUrl 需要拼接 minIO文章服务器的前缀路径
        List<SearchArticleVO> list = (List<SearchArticleVO>) searchResult.getData();
        if (CollectionUtils.isNotEmpty(list)) {
            for (SearchArticleVO searchArticleVo : list) {
                String images = searchArticleVo.getImages();
                if (StringUtils.isNotBlank(images)) {
                    images = Arrays.stream(images.split(",")).map(url -> website + url).collect(Collectors.joining(","));
                    searchArticleVo.setImages(images);
                }
                searchArticleVo.setStaticUrl(readPath + searchArticleVo.getStaticUrl());
            }
        }
        return searchResult;
    }

    /**
     * 添加索引文章
     * @param article
     */
    @Override
    public void saveArticle(SearchArticleVO article) {
        esService.save(article, EsConstants.ARTICLE_INDEX_NAME);
    }

    /**
     * 删除索引文章
     * @param articleId
     */
    @Override
    public void deleteArticle(String articleId) {
        esService.deleteById(articleId, EsConstants.ARTICLE_INDEX_NAME);
    }
}